package net.dgg.dggcloud.service.jrcrm.service.orf;

import net.dgg.dggcloud.core.json.JsonUtil;
import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.NJCodeUtil;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.entity.org.OrganizationEntity;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.service.sc.ScProOrderService;
import net.dgg.dggcloud.service.jrcrm.constant.BusinessConstant;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.constant.OrderConstant;
import net.dgg.dggcloud.service.jrcrm.dao.orf.OrderDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.business.BusinessDto;
import net.dgg.dggcloud.service.jrcrm.entity.cms.TreeBook;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.jrcrm.entity.customer.ReturnVisitCustomer;
import net.dgg.dggcloud.service.jrcrm.entity.orf.Order;
import net.dgg.dggcloud.service.jrcrm.entity.orf.OrderContact;
import net.dgg.dggcloud.service.jrcrm.entity.orf.OrderCustomer;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessAbilityService;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessService;
import net.dgg.dggcloud.service.jrcrm.service.cms.BillNumberRuleService;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import net.dgg.dggcloud.service.jrcrm.service.cms.MessageService;
import net.dgg.dggcloud.service.jrcrm.service.cms.TreeBookService;
import net.dgg.dggcloud.service.jrcrm.service.customer.CustomerService;
import net.dgg.dggcloud.service.jrcrm.service.customer.ReturnVisitCustomerService;
import net.dgg.dggcloud.service.jrcrm.service.customer.api.ContactApiService;
import net.dgg.dggcloud.service.jrcrm.service.customer.api.CustomerApiService;
import net.dgg.dggcloud.service.jrcrm.utils.TranslateMapUtil;
import net.dgg.dggcloud.service.service.organization.OrganizationService;
import net.dgg.dggcloud.service.service.user.UserService;
import net.dgg.framework.tac.mq.rabbitmq.queue.DggMessageSendUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 鲜林材
 *         ${DESCRIPTION}
 * @create 2017-11-03 11:40
 **/
@Service
public class OrderService extends BaseService {

    @Autowired
    private OrderDao orderDao;


    @Autowired
    private OrderCustomerService orderCustomerService;//订单客户信息

    @Autowired
    private OrderBusinessService orderBusinessService;//子订单表

    @Autowired
    private OrderContactService orderContactService;//订单联系

    @Resource
    private BillNumberRuleService bs;

    @Resource
    private BusinessAbilityService businessAbilityService;

    @Resource
    private ContactApiService contactApiService;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private UserService userService;

    @Resource
    private PerformanceService performanceService;

    @Resource
    private CustomerApiService customerApiService;

    @Resource
    private ScProOrderService scProOrderService;//生产订单

    @Resource
    private MessageService messageService;//消息发送

    @Resource
    private ReturnVisitCustomerService returnVisitCustomerService;//回访记录

    @Resource
    private NJCodeUtil nJCodeUtil;

    @Resource
    private CustomerService customerService;//回访记录

    @Resource
    private CustomerRecordService customerRecordService;


    @Autowired
    private TreeBookService  treeBookService;

    private static String messageQueName="com.door.msg.messageConsumer";

    @Autowired
    private BusinessService businessService;//商务

    /**
     * 通过客户id查询订单信息，新增时间降序
     *
     * @param customerId
     * @return
     */
    public List<Map> queryOrderListByCustomerId(String customerId) {
        List<Map> maps = new ArrayList<>();
        if (StringUtils.isNotEmpty(customerId)) {
            Map map = new HashMap();
            map.put("customerId", customerId);
            maps = orderDao.queryOrderListByCustomerIdByMap(map);
        }
        return maps;
    }

    /**
     * 通过商机id查询订单信息
     *
     * @param businessId
     * @return
     */
    public List<Map> queryOrderByBusinessId(String businessId) {
        Map map = new HashMap();
        if (StringUtils.isNotEmpty(businessId)) {
            map.put("businessId", businessId);
            List<Map> maps = orderDao.queryOrderListByMap(map);
            return maps;
        } else {
            throw new BizException("商机id不能为空！", 10006);
        }
    }


    /**
     * 保存订单
     *
     * @param order
     * @param user
     */
    @Transactional
    public void saveOrder(Order order, User user) {
        try {
            order.setCreateUser(user);
            order.setOrderNo(bs.updateBillNumberByCode("DD"));//订单编号
            order.setId(this.keyWorker.nextId());
            this.repository.save(order);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("保存订单异常:" + e.getMessage(), 10006);
        }
    }

    /**
     * 通过实体对应的属性，查询信息
     *
     * @param properName
     * @param value
     * @return
     */
    public List<Order> queryOrder(String properName, Object value) {
        return this.repository.findByProperty(Order.class, properName, value);
    }

    /**
     * 通过map查询订单信息
     *
     * @param map 查询条件 <br/>
     *            customerId  客户ID <br/>
     *            businessId  商机ID <br/>
     * @return
     */
    public List<Map> queryOrderListByMap(Map map) {
        return orderDao.queryOrderListByMap(map);
    }

    /**
     * 根据ID，获取订单
     *
     * @param id
     * @return
     */
    public Order getByIdHiber(Long id) {
        return this.repository.get(Order.class, id);
    }


    /**
     * 下单
     *
     * @param map  传输条件
     *             loaninfos 借款人信息 <br/>
     *             order 订单信息  <br/>
     *             subjectInfos 包装费信息 <br/>
     *             businesInfos  业务信息  <br/>
     *             customerPropertys  客户属性信息 <br/>
     *             customerDataInfos  客户资料信息   <br/>
     *             status  订单状态 必传 <br/>
     * @param user 用户信息
     */
    @Transactional
    public void savePlaceOrder(Map map, User user,Customer customer) {
        try {
            Order order = (Order) map.get("order");
            String subjectInfos = map.get("subjectInfos") == null ? null : map.get("subjectInfos").toString();
            String customerPropertys = map.get("customerPropertys") == null ? null : map.get("customerPropertys").toString();
            String customerDataInfos = map.get("customerDataInfos") == null ? null : map.get("customerDataInfos").toString();
            Long interFaceFlag = order.getId();//用于新增，修改区分标志
            Map commonParamsMap = saveHandlerPlaceOrder(user, order);
            map.put("user", commonParamsMap.get("user"));
            Long orderId = (Long) commonParamsMap.get("orderId");
            String orderNo = (String) commonParamsMap.get("orderNo");
            map.put("orderId", orderId);
            map.put("orderNo", orderNo);
            map.put("status", order.getStatus());
            orderContactService.saveOrUpdateBatchOrderContact(map);//保存订单联系人信息

            String orderBusiness = orderBusinessService.saveOrUpdateBatchOrderBusiness(map);//保存子订单信息
            OrderCustomer orderCustomer = new OrderCustomer(subjectInfos, customerPropertys, customerDataInfos);//客户
            orderCustomer.setAddress(customer.getAddress());
            orderCustomer.setAge(customer.getAge());
            orderCustomer.setBirthday(customer.getBirthday());
            orderCustomer.setCustomerName(customer.getName());
            orderCustomer.setEduBackground(customer.getEduBackground());
            orderCustomer.setChildrenNum(customer.getChildrenNum());
            orderCustomer.setIdCard(customer.getIdCard());
            orderCustomer.setEmail(customer.getEmail());
            orderCustomer.setMaritalStatus(customer.getMaritalStatus());
            orderCustomer.setRegisteredResidence(customer.getRegisteredResidence());
            orderCustomer.setSex(customer.getSex());

            orderCustomer.setOrderId((Long) commonParamsMap.get("orderId"));
            Long customerRelationId = (Long) map.get("customerRelationId");
            if (customerRelationId != null) {
                orderCustomer.setId(customerRelationId);
            }
            orderCustomerService.saveOrUpdateOrderCustomer(orderCustomer, user);
            Customer newCustomer = customerService.findCustomerById(customer.getId());
            newCustomer.setAddress(customer.getAddress());
            newCustomer.setAge(customer.getAge());
            newCustomer.setBirthday(customer.getBirthday());
            newCustomer.setName(customer.getName());
            newCustomer.setEduBackground(customer.getEduBackground());
            newCustomer.setChildrenNum(customer.getChildrenNum());
            newCustomer.setIdCard(customer.getIdCard());
            newCustomer.setEmail(customer.getEmail());
            newCustomer.setMaritalStatus(customer.getMaritalStatus());
            newCustomer.setRegisteredResidence(customer.getRegisteredResidence());
            newCustomer.setSex(customer.getSex());
            //设置vip 卡使用次数
            if (newCustomer.getIsBuyVip() != null){
                if (newCustomer.getIsBuyVip() == 1 && customer.getVipCardUseNumer() == null){
                    newCustomer.setVipCardUseNumer(0);
                }else {
                    newCustomer.setVipCardUseNumer(customer.getVipCardUseNumer());
                }
            }
            customerService.updateCustomer(newCustomer);
            //下单
            if (OrderConstant.ORF_DDZT_2.equals(order.getStatus())) {
                //调用客户内部接口
                updateCusInterfaceOfOverOrder(map, user, order);
                //调用生产订单接口
                updateScOrderAndScProOrder(commonParamsMap.get("order"), orderBusiness);
            }
            String auditUpdateFlag = (String) map.get("auditUpdateFlag");//审核修改标示
            if (interFaceFlag == null) {

                Business business = businessService.getBusinessById(order.getBusinessId());
                if(null != business && null != business.getFollowerId() && business.getFollowerId().longValue()!=user.getId().longValue()){
                    businessService.grapToFollow(order.getBusinessId(), user);
                }
                //修改商机状态
                updateBusInterfaceOfOverOrder(map, user, order, CustomerRecordConstant.BUS_OPERATE_ORDER);
                //发消息
                if(null != order.getSignOrgId()) {
                    TreeBook treeBook = treeBookService.queryTreeBookByCode(order.getSignOrgId().toString());
                    if(null != treeBook && null != treeBook.getExt5() && "open".equals(treeBook.getExt5().trim())){
                        BusinessDto businessDto = new BusinessDto();
                        businessDto.setLoginName(user.getLoginName());
                        businessDto.setNo(order.getBusinessNo());
                        businessDto.setOperationing("order");
                        DggMessageSendUtil.putMessage(messageQueName, businessDto);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("下单异常：" + e.getMessage(), 10006);
        }

    }

    /**
     * 调用内部接口：订单完成接口(商机)
     *
     * @param map
     * @param user
     * @param order
     */
    @Transactional
    public void updateBusInterfaceOfOverOrder(Map map, User user, Order order, String status) {
        try {
            //修改状态
            businessAbilityService.updateBusinessOrderInfo(order, user.getId(), status);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("订单完成调用商机接口!" + e.getMessage());
            throw new BizException(e.getMessage(), 10006);
        }
    }

    /**
     * 调用内部接口：订单完成接口(客户)
     *
     * @param map
     * @param user
     * @param order
     */
    @Transactional
    public void updateCusInterfaceOfOverOrder(Map map, User user, Order order) {
        try {
            //此处修改客户信息接口
            Object loaninfos = map.get("loaninfos");
            if (null != loaninfos) {
                Map contactMap = converCustomerContact(loaninfos.toString(), order.getCustomerId());
                contactMap.put("User", map.get("user"));
                contactApiService.updateContact(contactMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("订单完成调用客户接口!" + e.getMessage());
            throw new BizException(e.getMessage(), 10006);
        }
    }

    /**
     * 传输生产订单
     *
     * @param transOrder           :主订单
     * @param orderBusiness:子订单Map orderMap,List orderBusinessMap
     */
    private void updateScOrderAndScProOrder(Object transOrder, String orderBusiness) {
        try {
            if (transOrder != null) {
                String orderJson = JsonUtil.obj2Json(transOrder);
                Map transOrderMap = JsonUtil.json2Obj(orderJson, Map.class);//主订单
                List<Map> orderBusinessMap = new ArrayList();
                if (StringUtils.isNotEmpty(orderBusiness)) {
                    orderBusinessMap = JsonUtil.json2Obj(orderBusiness, List.class);
                }
                transOrderMap = getProduceOrder(transOrderMap);
                List<Map> productBusinessOrder = getProductBusinessOrder(transOrderMap, orderBusinessMap);
                scProOrderService.saveScOrderAndScProOrder(transOrderMap, productBusinessOrder);
                productBusinessOrder = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("传输生产订单异常" + e.getMessage());
            throw new BizException("传输生产订单异常:" + e.getMessage(), 10006);
        }

    }

    /**
     * 封装子订单生产订单数据
     *
     * @param orderMap:订单数据
     * @param orderBusinessMap：子订单数据
     * @return
     */
    private List<Map> getProductBusinessOrder(Map orderMap, List<Map> orderBusinessMap) {
        if (!orderBusinessMap.isEmpty()) {
            for (Map businessMap : orderBusinessMap) {
                if (businessMap != null) {
                    businessMap.put("orderId", orderMap.get("orderId"));//销售订单
                    businessMap.put("orderNo", orderMap.get("orderNo"));//销售订单编号
                    businessMap.put("orderBusId", businessMap.get("id"));//销售子订单ID
                    businessMap.remove("id");
                    businessMap.put("orderBusNo", businessMap.get("orderBusinessNo"));//生产订单
                    businessMap.put("businessId", orderMap.get("businessId"));//商机id
                    businessMap.put("businessNo", orderMap.get("businessNo"));//商机编号
                    businessMap.put("customerId", orderMap.get("customerId"));//客户id
                    businessMap.put("customerName", orderMap.get("customerName"));//客户名字
                    businessMap.put("customerPhone", orderMap.get("customerPhone"));//客户电话
                   /* Object businessCreateTime = businessMap.get("createTime");//创建时间
                    if(businessCreateTime!=null){
                        businessMap.put("createTime", DateUtil.convertNumberToString(Long.parseLong(businessCreateTime.toString())));
                    }
                    Object businessUpdateTime = businessMap.get("updateTime");//修改时间
                    if(businessUpdateTime!=null){
                        businessMap.put("updateTime",DateUtil.convertNumberToString(Long.parseLong(businessUpdateTime.toString())));
                    }*/
                }
            }
        }
        return orderBusinessMap;
    }

    /**
     * 封装生产订单数据
     *
     * @param orderMap
     * @return
     */
    private Map getProduceOrder(Map orderMap) {
        orderMap.put("orderId", orderMap.get("id"));//销售订单id
        orderMap.remove("id");//删除主键id
        Object loansAmount = orderMap.get("loansAmount");//贷款金额
        Object placeOrderTime = orderMap.get("placeOrderTime");//下单时间
        if (placeOrderTime != null) {
            orderMap.put("placeOrderTime", DateUtil.convertNumberToString(Long.parseLong(placeOrderTime.toString())));
        }
        Object createTime = orderMap.get("createTime");//创建时间
        if (createTime != null) {
            orderMap.put("createTime", DateUtil.convertNumberToString(Long.parseLong(createTime.toString())));
        }
        Object updateTime = orderMap.get("updateTime");//修改时间
        if (updateTime != null) {
            orderMap.put("updateTime", DateUtil.convertNumberToString(Long.parseLong(updateTime.toString())));
        }

        orderMap.remove("id");//删除主键id
        return orderMap;
    }

    /**
     * 转换值的属性
     *
     * @param loaninfos
     * @param customerId
     * @return
     */
    private Map converCustomerContact(String loaninfos, Long customerId) {
        Map result = new HashMap();
        List<Map> contactInfo = JsonUtil.json2Obj(loaninfos.toString(), List.class);
        Customer customer = customerApiService.getCustomerById(customerId);
        for (Map map : contactInfo) {
            if ("ORF_JDRGX_1".equals(map.get("relationshipOfCus"))) {
                map.put("mainContactId", customer.getMainContactId());
                break;
            }
        }
        result.put("customerId", customerId);
        result.put("contactInfo", contactInfo);
        return result;
    }

    /**
     * 下单或者暂存
     *
     * @param user
     * @param order
     * @return
     */
    @Transactional
    public Map saveHandlerPlaceOrder(User user, Order order) {
        Map map = new HashMap();
        if (order != null && order.getId() != null) {
            //修改
            Order oldOrder = this.getByIdHiber(order.getId());
            oldOrder.setLoansNum(order.getLoansNum());
            oldOrder.setLoansAmount(order.getLoansAmount());
            oldOrder.setLoansInterest(order.getLoansInterest());
            oldOrder.setLoansRateType(order.getLoansRateType());
            oldOrder.setEarnestMoney(order.getEarnestMoney());
            oldOrder.setMortgageAddress(order.getMortgageAddress());
            oldOrder.setCustomerName(order.getCustomerName());
            oldOrder.setContactPhoneBak(order.getContactPhone());
            oldOrder.setContactPhone(nJCodeUtil.encrypt(order.getContactPhone()));
            oldOrder.setStatus(order.getStatus());
            if (order.getBusinessUserId() != null) {
                //(修改)防止商机跟进人变动
                User businessUser = userService.getUserById(order.getBusinessUserId());//签单商务
                if (businessUser.getOrgId() == null) {
                    throw new BizException("签单商务组织不存在！", 10006);
                }
                oldOrder.setOrganizationId(businessUser.getOrgId());//部门id
                OrganizationEntity depatemntEntity = organizationService.find4Id(businessUser.getOrgId());//部门实体
                if (depatemntEntity == null) {
                    throw new BizException("签单商务组织不存在！", 10006);
                }
                if (depatemntEntity.getLeaderId() == null) {
                    throw new BizException("签单商务领导不存在！", 10006);
                }
                oldOrder.setAuditUserId(depatemntEntity.getLeaderId());
                oldOrder.setOrganizationName(depatemntEntity.getName());//部门名称
                Long organizationDepartmentId = organizationService.getOrganizationDepartmentId(businessUser.getOrgId());//签单事业部id
                OrganizationEntity organizationEntity = organizationService.find4Id(organizationDepartmentId);//签单事业部名称
                if (organizationEntity != null) {
                    oldOrder.setSignOrgId(organizationDepartmentId);
                    oldOrder.setSignOrgName(organizationEntity.getName());
                }
            }
            if ("ORF_DDZT_2".equals(order.getStatus())) {
                //下单
                //oldOrder.setPlaceOrderTime(new Date());
                map.put("order", oldOrder);
            }
            this.updateOrder(oldOrder, user);
        } else {
            //新增
            if (order.getBusinessUserId() != null) {
                User businessUser = userService.getUserById(order.getBusinessUserId());//签单商务
                if (businessUser.getOrgId() == null) {
                    throw new BizException("签单商务组织不存在！", 10006);
                }
                order.setOrganizationId(businessUser.getOrgId());//部门id
                OrganizationEntity depatemntEntity = organizationService.find4Id(businessUser.getOrgId());//部门实体
                if (depatemntEntity == null) {
                    throw new BizException("签单商务组织不存在！", 10006);
                }
                if (depatemntEntity.getLeaderId() == null) {
                    throw new BizException("签单商务领导不存在！", 10006);
                }
                order.setAuditUserId(depatemntEntity.getLeaderId());//审核人id
                order.setOrganizationName(depatemntEntity.getName());//部门名称
                Long organizationDepartmentId = organizationService.getOrganizationDepartmentId(businessUser.getOrgId());//签单事业部id
                OrganizationEntity organizationEntity = organizationService.find4Id(organizationDepartmentId);//签单事业部名称
                if (organizationEntity != null) {
                    order.setSignOrgId(organizationDepartmentId);
                    order.setSignOrgName(organizationEntity.getName());
                }
            }
            if ("ORF_DDZT_2".equals(order.getStatus())) {
                //下单
                //order.setPlaceOrderTime(new Date());
            }
            order.setPlaceOrderTime(new Date());
            order.setContactPhoneBak(order.getContactPhone());
            order.setContactPhone(nJCodeUtil.encrypt(order.getContactPhone()));
            this.saveOrder(order, user);//保存订单主表信息
            map.put("order", order);
        }
        map.put("user", user);
        map.put("orderId", order.getId());
        map.put("orderNo", order.getOrderNo());
        return map;
    }


    /**
     * 选择订单列表
     * BusinessUserId  签单商务
     * keyword 客户名称，订单编号
     *
     * @param map
     * @return
     */
    public List<Map> listSelectOrder(Map map) {
        return orderDao.listSelectOrderByMap(map);
    }

    /**
     * 订单接口列表
     * BusinessUserId  签单商务
     * keyword 客户名称，订单编号
     *
     * @param map
     * @return
     */
    public List<Map> listReferralOrder(Map map) {
        return orderDao.listReferralOrderByMap(map);
    }

    /**
     * 选择订单列表
     * BusinessUserId  签单商务
     * keyword 客户名称，订单编号
     *
     * @param map
     * @return
     */
    public Integer countListSelectOrder(Map map) {
        return orderDao.countListSelectOrder(map);
    }


    /**
     * 选择订单列表 退款
     * BusinessUserId  签单商务
     * keyword 客户名称，订单编号
     *
     * @param map
     * @return
     */
    public List<Map> listReimburseSelectOrder(Map map) {
        return orderDao.listReimburseSelectOrder(map);
    }

    /**
     * 选择订单列表 退款
     * BusinessUserId  签单商务
     * keyword 客户名称，订单编号
     *
     * @param map
     * @return
     */
    public Integer countReimburseListSelectOrder(Map map) {
        return orderDao.countReimburseSelectOrder(map);
    }


    /**
     * 更新订单
     *
     * @param order
     * @param user
     */
    @Transactional
    public void updateOrder(Order order, User user) {
        try {
            order.setUpdaterUser(user);
            this.repository.saveOrUpdate(order);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("更新订单异常" + e.getMessage(), 10006);
        }
    }


    /**
     * 查询已完成的订单数量通过客户id
     *
     * @return
     */
    public int queryOrderFinishByCustomerId(Long customerId) {
        Map map = new HashMap();
        map.put("customerId", customerId);
        map.put("status", "'" + OrderConstant.ORF_DDZT_5 + "'");
        return orderDao.countListSelectOrder(map);
    }

    /**
     * 通过map查询订单信息分页信息
     *
     * @param paramMap
     * @return
     */
    public List<Map> queryOrderListPageByMap(Map paramMap) {
        return orderDao.queryOrderListPageByMap(paramMap);
    }

    /**
     * 查询分页总数通过map
     *
     * @param paramMap
     * @return
     */
    public Integer countlistOrdersPageByMap(Map paramMap) {
        return orderDao.countlistOrdersPageByMap(paramMap);
    }

    /**
     * 查询财务核款记录信息通过订单id
     *
     * @param id
     * @return
     */
    public List<Map> queryFinancialOfOrderBYOrderId(long id) {
        return performanceService.queryTotoalOfOrderBYOrderId(id);
    }

    /**
     * 回调订单
     *
     * @param orderId         ：订单id <br/>
     * @param backOrderReason ：订单原因 <br/
     * @param user            :用户 <br/
     */
    public void backOrder(Long orderId, String backOrderReason, User user) {
        try {
            Map map = new HashMap();
            map.put("orderId", orderId);
            map.put("backOrderTime", DateUtil.dateToString(new Date()));
            map.put("backOrderReason", backOrderReason);
            map.put("status", OrderConstant.ORF_DDZT_3);//状态退单
            map.put("updateTime", DateUtil.dateToString(new Date()));
            map.put("updaterId", user.getId());
            map.put("updaterName", user.getName() + user.getLoginName());
            map.put("updaterOrgId", user.getOrgId());
            orderDao.updateOrderByMap(map);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("订单回退异常");
            throw new BizException("订单回退异常", 10006);
        }
    }

    /**
     * 查询订单预览信息通过订单id <br/>
     *
     * @param orderId <br/>
     * @return
     */
    public Map queryPreviewOrderById(String orderId) {
        Map map = new HashMap();
        map.put("id", orderId);
        List<Map> results = orderDao.queryPreviewOrderByMap(map);
        if (!results.isEmpty()) {
            return results.get(0);
        }
        return null;
    }

    /**
     * 通过客户id查询订单历史信息 <br/>
     *
     * @param customerId 客户id</br>
     * @return
     */
    public List<Map> queryOrderHitoryByCustomerId(Long customerId) {
        if (customerId == null) {
            throw new BizException("查询订单历史信息：客户id为null", 10006);
        }
        List<Map> list = orderDao.queryOrderHitoryByCustomerId(customerId);
        String[] column = {"status"};//需要翻译的列， List<Map>中Map的key
        list = TranslateMapUtil.translateMap(column, list);
        return list;
    }

    /**
     * 更新订单
     *
     * @param order
     */
    @Transactional
    public void updateOrder(Order order) {
        try {
            this.repository.saveOrUpdate(order);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("更新订单异常" + e.getMessage(), 10006);
        }
    }

    /**
     * 查询订单信息通过商机id和当前跟前人
     *
     * @param businessMap
     * @return
     */
    public List<Map> queryOrderByBusinessByMap(Map businessMap) {
        return orderDao.queryOrderByBusinessByMap(businessMap);
    }

    /**
     * 取消订单
     *
     * @param orderId 订单id
     * @param user    用户
     */
    @Transactional
    public void removerOrder(long orderId, User user) {
        try {
          /*  Order order = this.getByIdHiber(orderId);
            Map map=new HashMap();
            List<OrderBusiness> business=orderBusinessService.queryOrderBusinessByOrderId(orderId);
            for ( OrderBusiness orderBusines:business) {
                orderBusines.setUpdaterUser(user);
                orderBusines.setStatus(OrderConstant.ORF_DDZT_7);
                orderBusinessService.updateOrderBusiness(orderBusines);
            }
            order.setStatus(OrderConstant.ORF_DDZT_7);
            order.setUpdaterUser(user);
            this.updateOrder(order);*/
            Order order = this.getByIdHiber(orderId);
            //修改商机为跟进中
            businessAbilityService.updateBusinessOrderInfo(order, user.getId(), CustomerRecordConstant.BUS_OPERATE_ORDER_BACK);
            Map parameterMap = new HashMap();
            parameterMap.put("orderId", orderId);
            orderDao.deleteOrderByMap(parameterMap);
            orderBusinessService.deleteOrderBusinessByMap(parameterMap);
            orderContactService.deleteOrderContactByMap(parameterMap);
            orderCustomerService.deleteOrderCustomerByMap(parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("订单取消异常" + e.getMessage());
            throw new BizException("订单取消异常:" + e.getMessage(), 10006);
        }
    }

    /**
     * 查询待审核订单
     *
     * @param paramMap
     * @return
     */
    public List<Map> queryAuditOrderListPageByMap(Map paramMap) {
        return orderDao.queryAuditOrderListPageByMap(paramMap);
    }

    /**
     * 审核订单总数
     *
     * @param paramMap
     * @return
     */
    public Integer countAuditOrderListPageByMap(Map paramMap) {
        return orderDao.countAuditOrderListPageByMap(paramMap);
    }

    /**
     * 订单审核修改通过
     *
     * @param requestMap
     * @param user
     */
    @Transactional
    public void updateAuditPassOrders(Map<String, Object> requestMap, User user) {
        String orderIds = (String) requestMap.get("orderIds");
        String[] orders = orderIds.split(",");
        Map parameterMap = null;
        try {
            if (orders != null && orders.length > 0) {
                for (String orderId : orders) {
                    if (StringUtils.isNotEmpty(orderId)) {
                        Order order = this.getByIdHiber(Long.parseLong(orderId));
                        if (!"ORF_DDZT_8".equals(order.getStatus())) {
                            throw new BizException("订单审核过了，请刷新页面重试！", 10006);
                        }
                        parameterMap = new HashMap();
                        String nowTime = DateUtil.dateToString(new Date());
                        parameterMap.put("orderId", orderId.trim());
                        parameterMap.put("status", OrderConstant.ORF_DDZT_2);//状态退单
                        parameterMap.put("updateTime", nowTime);
                        parameterMap.put("updaterId", user.getId());
                        parameterMap.put("updaterName", user.getName() + user.getLoginName());
                        parameterMap.put("updaterOrgId", user.getOrgId());
                        //parameterMap.put("placeOrderTime", nowTime);
                        parameterMap.put("auditOrderTime", DateUtil.dateToString(new Date()));
                        orderDao.updateOrderByMap(parameterMap);
                        Map orderQueryMap = new HashMap();
                        orderQueryMap.put("orderId", orderId);
                        List<Map> orderMaps = this.queryOrderListByMap(orderQueryMap);
                        Map orderMap = orderMaps.get(0);
                        Long customerId = Long.parseLong(orderMap.get("customerId").toString());
                        Long businessId = Long.parseLong(orderMap.get("businessId").toString());
                        Customer customer = customerApiService.getCustomerById(customerId);
                        //调用内部接口
                        updateInternalOfOrder(user, parameterMap, orderMap, customer);
                        //修改生产接口
                        updateScProOrder(orderId, orderMap);
                        //新增一条回访记录
                        insertReturnVisitCustomer(user, customerId, businessId);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("订单审核信息异常" + e.getMessage());
            throw new BizException("订单审核信息异常:" + e.getMessage(), 10006);
        }
    }

    /**
     * 新增客户回访记录
     *
     * @param user
     * @param customerId
     * @param businessId
     */
    @Transactional
    protected void insertReturnVisitCustomer(User user, Long customerId, Long businessId) {
        ReturnVisitCustomer rvc = new ReturnVisitCustomer();
        rvc.setCreateUser(user);
        rvc.setUpdaterUser(user);
        rvc.setCustomerId(customerId);
        rvc.setLastBusId(businessId);
        returnVisitCustomerService.saveOrUpdateReturnVisitCustomer(rvc);
    }

    /**
     * 调用生产接口
     *
     * @param orderId
     * @param orderMap
     */
    @Transactional
    protected void updateScProOrder(String orderId, Map orderMap) {
        try {
            Map orderBusinesMap = new HashMap();
            orderBusinesMap.put("orderId", orderId);
            Map produceOrder = getProduceOrderFromDatabase(orderMap);
            List<Map> orderBusinessOrder = orderBusinessService.queryOrderBusinessByMap(orderBusinesMap);
            List<Map> productBusinessOrder = getProductBusinessOrderFromDatabase(orderMap, orderBusinessOrder);
            scProOrderService.saveScOrderAndScProOrder(produceOrder, productBusinessOrder);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("调用生产接口异常：" + e.getMessage());
            throw new BizException("调用生产接口异常:" + e.getMessage(), 10006);
        }

    }

    /**
     * 更新系统内部接口
     *
     * @param user
     * @param parameterMap:查询参数
     * @param orderMap
     * @param customer
     */
    @Transactional
    protected void updateInternalOfOrder(User user, Map parameterMap, Map orderMap, Customer customer) {
        try {
            //修改商机接口
            // businessAbilityService.updateBusinessOrderInfo(Long.parseLong(orderMap.get("businessId").toString()),user.getId(), CustomerRecordConstant.BUS_OPERATE_ORDER);
            //此处修改客户信息接口
            List<Map> orderContacts = orderContactService.queryOrderContactListByMap(parameterMap);
            Long orderContactId = null;
            if (!orderContacts.isEmpty()) {
                Map contactMap = new HashMap();

                for (Map map : orderContacts) {
                    /*if("ORF_JDRGX_1".equals(map.get("relationshipOfCus"))){
                        map.put("mainContactId",customer.getMainContactId());
                        break;
                    }*/
                    if (map.get("mainContactId") != null) {
                        orderContactId = Long.parseLong(map.get("id").toString());
                    }
                    if (1 == Integer.parseInt(map.get("isSelf").toString())) {
                        map.put("id", orderMap.get("customerId"));
                        map.put("businessId", orderMap.get("businessId"));
                        map.put("User", user);
                        map.put("idCard", map.get("cardId"));
                        map.put("customerPhone", map.get("no"));
                        customerApiService.updateCustomer(map);
                    }

                }
                contactMap.put("customerId", orderMap.get("customerId"));
                contactMap.put("contactInfo", orderContacts);
                contactMap.put("User", user);
                Long mainContactId = contactApiService.updateContact(contactMap);
                if (mainContactId != null && orderContactId != null) {
                    OrderContact orderContact = orderContactService.getByIdHiber(orderContactId);
                    orderContact.setMainContactId(mainContactId);
                    orderContactService.updateOrderContact(orderContact, user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("订单下单审核内部接口调用异常！" + e.getMessage());
            throw new BizException("内部接口调用异常：" + e.getMessage(), 10006);
        }
    }


    /**
     * 封装生产订单数据(防止对方转换数据出错，mindao查询出来小写，对方转换对象为null)
     *
     * @param orderMap
     * @return
     */
    private Map getProduceOrderFromDatabase(Map orderMap) {
        Map resultMap = new HashMap();
        resultMap.put("orderId", orderMap.get("id"));//销售订单id
        resultMap.put("amount", orderMap.get("amount"));
        resultMap.put("receivableAmount", orderMap.get("receivableamount"));
        resultMap.put("orderNo", orderMap.get("orderno"));
        resultMap.put("businessId", orderMap.get("businessid"));
        resultMap.put("businessNo", orderMap.get("businessno"));
        resultMap.put("contactPhone", orderMap.get("contactphone"));
        resultMap.put("customerName", orderMap.get("customername"));
        resultMap.put("customerId", orderMap.get("customerid"));
        resultMap.put("internalCost", orderMap.get("internalcost"));
        resultMap.put("externalCost", orderMap.get("externalcost"));
        resultMap.put("customerNo", orderMap.get("customerno"));
        resultMap.put("paySatus", orderMap.get("paysatus"));
        resultMap.put("businessTypeId", orderMap.get("businesstypeId"));
        resultMap.put("businessTypeName", orderMap.get("businesstypeName"));
        resultMap.put("businessUserId", orderMap.get("businessuserId"));
        resultMap.put("status", orderMap.get("status"));
        resultMap.put("organizationId", orderMap.get("organizationid"));
        resultMap.put("organizationName", orderMap.get("organizationname"));
        resultMap.put("achievement", orderMap.get("achievement"));
        resultMap.put("signOrgId", orderMap.get("signorgid"));
        resultMap.put("signOrgName", orderMap.get("signorgname"));
        resultMap.put("loansAmount", orderMap.get("loansamount"));
        resultMap.put("loansNum", orderMap.get("loansnum"));
        resultMap.put("loansInterest", orderMap.get("loansinterest"));
        resultMap.put("earnestMoney", orderMap.get("earnestmoney"));
        resultMap.put("loansRateType", orderMap.get("loansratetype"));
        resultMap.put("mortgageAddress", orderMap.get("mortgageaddress"));
        resultMap.put("placeOrderTime", orderMap.get("placeordertime"));
        resultMap.put("backOrderTime", orderMap.get("backordertime"));
        resultMap.put("backOrderReason", orderMap.get("backorderreason"));
        return resultMap;
    }


    /**
     * 封装子订单生产订单数据 mindao查询出来小写，对方转换对象为null)
     *
     * @param orderMap:订单数据
     * @param orderBusinessMap：子订单数据
     * @return
     */
    private List<Map> getProductBusinessOrderFromDatabase(Map orderMap, List<Map> orderBusinessMap) {
        List<Map> result = new ArrayList<>();
        Map map = null;
        if (!orderBusinessMap.isEmpty()) {
            for (Map businessMap : orderBusinessMap) {
                if (businessMap != null) {
                    map = new HashMap();
                    map.put("orderId", orderMap.get("id"));//销售订单
                    map.put("orderNo", orderMap.get("orderNo"));//销售订单编号
                    map.put("businessId", orderMap.get("businessId"));//商机id
                    map.put("businessNo", orderMap.get("businessNo"));//商机编号
                    map.put("customerId", orderMap.get("customerId"));//客户id
                    map.put("customerName", orderMap.get("customerName"));//客户名字
                    map.put("customerPhone", orderMap.get("customerPhone"));//客户电话
                    map.put("orderBusId", businessMap.get("id"));//销售子订单ID
                    map.put("orderBusNo", businessMap.get("orderBusinessNo"));//生产订单
                    map.put("status", businessMap.get("status"));
                    map.put("btName", businessMap.get("btName"));
                    map.put("btCode", businessMap.get("btIdentifying"));
                    map.put("typeIdentifying", businessMap.get("typeIdentifying"));
                    map.put("productId", businessMap.get("productId"));
                    map.put("serviceCharge", businessMap.get("serviceCharge"));
                    map.put("rateType", businessMap.get("rateType"));
                    map.put("loansAmount", businessMap.get("loansAmount"));
                    map.put("flowUserId", businessMap.get("flowUserId"));
                    map.put("contractNo", businessMap.get("contractNo"));
                    map.put("channelId", businessMap.get("channelId"));
                    map.put("organizationId",businessMap.get("organizationId"));//新加事业部id
                    result.add(map);
                }
            }
        }
        return result;
    }

    /**
     * 修改审核拒绝订单
     *
     * @param orderIds               :订单id数组
     * @param auditRejectReason:拒绝原因
     */
    @Transactional
    public void updateAuditRejectOrders(String orderIds, String auditRejectReason, User user) {
        try {
            String[] orders = orderIds.split(",");
            Map parameterMap = new HashMap();
            if (orders != null && orders.length > 0) {
                for (String orderId : orders) {
                    if (StringUtils.isNotEmpty(orderId)) {
                        parameterMap = new HashMap();
                        Order order = this.getByIdHiber(Long.parseLong(orderId));
                        if (!"ORF_DDZT_8".equals(order.getStatus())) {
                            throw new BizException("订单审核过了，请刷新页面重试！", 10006);
                        }
                        parameterMap.put("orderId", orderId.trim());
                        parameterMap.put("status", OrderConstant.ORF_DDZT_9);//状态退单
                        parameterMap.put("updateTime", DateUtil.dateToString(new Date()));
                        parameterMap.put("updaterId", user.getId());
                        parameterMap.put("updaterName", user.getName() + user.getLoginName());
                        parameterMap.put("updaterOrgId", user.getOrgId());
                        parameterMap.put("auditRejectReason", auditRejectReason);
                        parameterMap.put("auditOrderTime", DateUtil.dateToString(new Date()));
                        orderDao.updateOrderByMap(parameterMap);
                        //消息调用
                        String orderNo = order.getOrderNo();
                        User receiverUser = new User();
                        receiverUser.setId(order.getBusinessUserId());
                        String vals[] = {order.getOrderNo()};
                        messageService.sendMessageReady(receiverUser, user, vals, "XS_JDBH_MSG");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("审核拒绝订单异常:" + e.getMessage());
            throw new BizException("审核拒绝订单异常:" + e.getMessage(), 10006);
        }
    }

    /**
     * 批量删除订单
     *
     * @param orderIds:订单数组
     * @param user
     */
    @Transactional
    public void removeBatchOrder(String orderIds, User user) {
        try {
            String[] ids = orderIds.split(",");
            Map parameterMap = new HashMap();
            if (ids != null && ids.length > 0) {
                for (String id : ids) {
                    if (StringUtils.isNotEmpty(id)) {
                        parameterMap = new HashMap();
                       /* parameterMap.put("orderId", id.trim());
                        parameterMap.put("status", OrderConstant.ORF_DDZT_7);//取消
                        parameterMap.put("updateTime", DateUtil.dateToString(new Date()));
                        parameterMap.put("updaterId", user.getId());
                        parameterMap.put("updaterName", user.getName() + user.getLoginName());
                        parameterMap.put("updaterOrgId", user.getOrgId());
                        orderDao.updateOrderByMap(parameterMap);*/
                        Order order = this.getByIdHiber(Long.parseLong(id));
                        //修改商机为跟进中
                        businessAbilityService.updateBusinessOrderInfo(order, user.getId(), CustomerRecordConstant.BUS_OPERATE_ORDER_BACK);
                        parameterMap.put("orderId", id.trim());
                        orderDao.deleteOrderByMap(parameterMap);
                        orderBusinessService.deleteOrderBusinessByMap(parameterMap);
                        orderContactService.deleteOrderContactByMap(parameterMap);
                        orderCustomerService.deleteOrderCustomerByMap(parameterMap);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("批量删除订单异常：" + e.getMessage());
            throw new BizException("批量删除订单异常:" + e.getMessage(), 10006);
        }

    }

    /**
     * 通过商机id，商机跟进人查询处理中的订单状况 </br>
     *
     * @param paramMap </br>
     *                 businessId ：商机id </br>
     *                 businessUserId: 当前商机跟进人</br>
     * @return true:可下单，false:不可下单
     */
    public boolean getOrderStateofBusiness(Map paramMap) {
        String status = "1";//可下单
        if (paramMap.get("businessId") == null) {
            throw new BizException("商机id不能为空！", 10006);
        }

        if (paramMap.get("businessUserId") == null) {
            throw new BizException("商机跟进人不能为空！", 10006);
        }
        paramMap.put("status", "'" + OrderConstant.ORF_DDZT_2 + "','" + OrderConstant.ORF_DDZT_8 + "'");//待审核状态、下单状态
        int count = orderDao.queryInProcessOfOrderByMap(paramMap);
        if (count > 0) {
            status = "0";//不可下单
        }
        paramMap.put("resultStatus", status);
        return status.equals("1");
    }


    public void updateOrderTransferUser(String orders, String userId) {
        try {
            if (StringUtils.isNotBlank(orders)) {
                for (String orderId : orders.split(",")) {
                    Order order = getByIdHiber(Long.parseLong(orderId));
                    order.setTransferUserId(Long.parseLong(userId));
                    this.repository.saveOrUpdate(order);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("批量更新订单移交人异常：" + e.getMessage());
            throw new BizException("批量更新订单移交人异常:" + e.getMessage(), 10006);
        }

    }


    /**
     * 通过商机ids查询订单信息
     *
     * @param businessIds
     * @return
     */
    public List<Map> queryOrderByBusinessIds(String businessIds) {
        Map map = new HashMap();
        if (StringUtils.isNotEmpty(businessIds)) {
            map.put("businessIds", businessIds);
            List<Map> maps = orderDao.queryOrderListByMap(map);
            return maps;
        } else {
            throw new BizException("商机id不能为空！", 10006);
        }
    }

    public boolean addOrder(Business business,Customer customer,User user){
        try {
            Order order = new Order();
            order.setCreateUser(user);
            order.setOrderNo(bs.updateBillNumberByCode("DD"));//订单编号
            order.setId(this.keyWorker.nextId());
            order.setCustomerId(customer.getId());
            order.setBusinessId(business.getId());
            order.setBusinessNo(business.getNo());
            order.setBusinessUserId(user.getId());
            order.setCustomerName(customer.getName());
            order.setContactPhoneBak(nJCodeUtil.decrypt(customer.getCustomerPhone()==null?"":customer.getCustomerPhone().toString()));
            order.setContactPhone(customer.getCustomerPhone()==null?"":customer.getCustomerPhone().toString());
            order.setCustomerNo(customer.getNo());
            order.setStatus("ORF_DDZT_1");
            order.setPlaceOrderTime(new Date());
            if (user.getOrgId() == null) {
                throw new BizException("签单商务组织不存在！", 10006);
            }
            order.setOrganizationId(user.getOrgId());//部门id
            OrganizationEntity depatemntEntity = organizationService.find4Id(user.getOrgId());//部门实体
            if (depatemntEntity == null) {
                throw new BizException("签单商务组织不存在！", 10006);
            }

            order.setOrganizationName(depatemntEntity.getName());//部门名称
            Long organizationDepartmentId = organizationService.getOrganizationDepartmentId(user.getOrgId());//签单事业部id
            OrganizationEntity organizationEntity = organizationService.find4Id(organizationDepartmentId);//签单事业部名称
            if (organizationEntity != null) {
                order.setSignOrgId(organizationDepartmentId);
                order.setSignOrgName(organizationEntity.getName());
            }


            this.repository.saveOrUpdate(order);


            //设置商机已签单
            //updateBusInterfaceOfOverOrder(null, user, order, CustomerRecordConstant.BUS_OPERATE_ORDER);

            business.setBusinessStatus(BusinessConstant.BUS_STATUS_SIGNED);
            business.setLastFollowRecordContent("签单");
            business.setOrderTime(new Date());
            business.setWillDropTime(null);

            business.setLastFollowRecordTime(new Date());
            business.setLastFollowRecordUser(user.getName() + user.getLoginName());
            business.setBusinessOperate(CustomerRecordConstant.BUS_OPERATE_ORDER);
            business.setUpdaterUser(user);
            //保存备注记录
            Map recordMap = new HashMap();
            recordMap.put("tableName", Business.TABLE_NAME);
            recordMap.put("tableId", business.getId());
            recordMap.put("cusId", business.getCustomerId());
            recordMap.put("recordType", CustomerRecordConstant.BUS_OPERATE_ORDER);
            recordMap.put("content", business.getLastFollowRecordContent());
            recordMap.put("ext3", business.getNo());//商机编号
            recordMap.put("toUserId", business.getFollowerId());//新的跟进人，这里为方便定时器的转化率统计，把商机跟进人放进去
            recordMap.put("toUserOrgId", business.getFollowerOrganizationId());//新的跟进人部门
            recordMap.put("ext1", business.getBusinessStage());//商机当前阶段
            recordMap.put("ext2", business.getBusinessLocation());//商机所在库
            recordMap.put("ext4", BusinessConstant.BUS_STATUS_SIGNED);//商机当前状态
            recordMap.put("ext3", business.getNo());//商机编号
            recordMap.put("operateUser", user.getId());
            customerRecordService.saveCustomerRecord(recordMap);
            repository.saveOrUpdate(business);

            //发消息
            if(161==organizationDepartmentId) {
                BusinessDto businessDto = new BusinessDto();
                businessDto.setLoginName(user.getLoginName());
                businessDto.setNo(business.getNo());
                businessDto.setOperationing("order");
                DggMessageSendUtil.putMessage(messageQueName, businessDto);
            }

            return true;

        }catch (Exception e){
            e.printStackTrace();
            throw new BizException("下单失败！"+e.getMessage(), 10006);
        }
    }
}
